package com.linsen.core.excel.convert;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.linsen.core.common.exception.BaseException;
import com.linsen.core.common.util.LocalDateTimeUtil;

import java.time.LocalDate;

/**
 * 用于解决使用easyExcel导出表格时候，默认不支持LocalDate日期格式
 * 在需要的属性上添加注解 @ExcelProperty(converter = LocalDateConverter.class)
 */
public class LocalDateConverter implements Converter<LocalDate> {

    @Override
    public Class<LocalDate> supportJavaTypeKey() {
        return LocalDate.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDate convertToJavaData(ReadCellData cellData, ExcelContentProperty contentProperty,
                                       GlobalConfiguration globalConfiguration) {
        LocalDate localDate = null;

        if (ObjectUtil.equal(cellData.getType(),CellDataTypeEnum.NUMBER)){
            String dataFormatString = cellData.getDataFormatData().getFormat();
            if (ObjectUtil.equal("General",dataFormatString)){//纯数字格式
                throw new BaseException("数据格式错误");
            }

            LocalDate firstDate = LocalDate.of(1900, 1, 1);
            //excel 有些奇怪的bug, 导致日期数差2
            localDate = firstDate.plusDays(cellData.getNumberValue().longValue() - 2);
        } else if (cellData.getType().equals(CellDataTypeEnum.STRING)) {
            try {
                localDate = LocalDate.parse(cellData.getStringValue(), LocalDateTimeUtil.YYYYMMDD);
            }catch (Exception e){
                throw new BaseException("数据格式错误");
            }
        }

        return localDate;
    }

    @Override
    public WriteCellData<String> convertToExcelData(LocalDate value, ExcelContentProperty contentProperty,
                                                    GlobalConfiguration globalConfiguration) {
        return new WriteCellData<>(value.format(LocalDateTimeUtil.YYYYMMDD));
    }
}